<template>
  <div>
    <el-dialog
    title="编辑套餐"
    :visible.sync="visible"
    width="50%"
    style="border-radius: 10px;"
    @close="handleClose"
  >
    <el-form
      ref="foodForm"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="dialogN"
      style="padding: 30px;padding-top: 10px;"
      label-position="top"
      size="medium"
    >
      <!-- 基本信息 -->
      <div style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;display: flex;letter-spacing: normal;color: #3D3D3D;">
        <img src="@/assets/images/updatesvn.svg" alt="信息图标" style="padding-right: 5px;">
        基本信息
      </div>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="套餐名称" prop="comboName">
            <el-input v-model="form.comboName" placeholder="请输入套餐名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="热量" prop="heat">
            <el-input v-model="form.heat" placeholder="请输入热量" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="现售价" prop="price">
            <el-input v-model="form.price" type="number" :min="0" placeholder="请输入现售价" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="原价" prop="originalPrice">
            <el-input v-model="form.originalPrice" type="number" :min="0" placeholder="请输入原价" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最大供应量" prop="num">
            <el-input v-model="form.num" type="number" @input="OnchangeInput" :min="0" placeholder="请输入最大供应量" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生效时间" prop="startDate">
            <el-date-picker
              style="width: 100%;"
              v-model="form.startDate"
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(item,index) in moldList"
                :key="index"
                :label="item.label"
                :value="Number(item.value)">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开放时间" prop="openingHours">
            <el-select v-model="form.openingHours" multiple placeholder="请选择" style="width: 100%;">
              <el-option
                v-for="(item,index) in openingHoursList"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="显示排序" prop="sort">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="最大限购(-1不限)" prop="limitPerUser">
            <el-input-number v-model="form.limitPerUser" controls-position="right" :min="-1" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8" v-hasPermi="['food:combo:approval']">
          <el-form-item label="状态" prop="status" v-if="form.status !=2 && form.status!=3">
            <el-select v-model="form.status" placeholder="请选择" style="width: 95%;">
              <el-option
                v-for="(item,index) in statusList"
                :key="index"
                :label="item.label"
                :value="String(item.value)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 套餐信息 -->
      <div style="font-size: 20px;font-weight: 600;padding: 12px 0; padding-right: 5px;margin-top: -4px;">
        <img src="@/assets/images/updatesvn.svg" alt="信息图标" style="padding-right: 3px;margin-top: -5px;">
        套餐信息
        <el-button plain style="background-color: rgb(237, 240, 252);color: #4C6EE2;border: 1px solid #4C6EE2;" @click="addIngredients">添加菜品</el-button>
        （总价格：{{totalPrice}}）
      </div>

      <el-row :gutter="20" v-for="(item,index) in form.listItem" :key="index">
        <el-col :span="8">
          <el-form-item 
            label="菜品类型" 
            :prop="`listItem.${index}.type`" 
            :rules="{ required: true, message: '请选择菜品类型', trigger: 'change'}" 
          >
            <el-select 
              v-model="item.type" 
              placeholder="请选择" 
              style="width: 100%;"
              clearable 
            >
               <el-option
                  v-for="(items,index) in dict.type.foot_cuisine_type"
                  :key="index"
                  :label="items.label"
                  :value="items.value"
                ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item 
            label="菜品"
            :prop="`listItem.${index}.foodDish.foodId`" 
            :rules="{ required: true, message: '请选择菜品', trigger: 'change'}"  
          >
            <el-select 
              v-model="item.foodDish.foodId" 
              placeholder="请选择" 
              style="width: 80%;"
              filterable
              clearable 
              @change="handleFoodChange(item.foodDish.foodId, item)"  
            >
              <el-option
                v-for="(food, i) in ingredientList"
                :key="i"
                :label="food.foodName"
                :value="food.foodId"
              >
                <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                  <span>{{ food.foodName }}</span>
                  <span style="color: #67C23A; font-weight: 500;">￥{{ food.price }}</span>
                </div>
              </el-option>
            </el-select>
            <i 
              class="el-icon-delete" 
              v-if="form.listItem.length > 1" 
              @click="deleteFoodItems(index)"
              style="margin-left: 5px; cursor: pointer;"
            ></i>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 其他信息 -->
      <el-form-item label="套餐描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入套餐描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="过敏源" prop="allergy">
        <el-input 
          v-model="form.allergy"
          type="textarea"
          :rows="3"
          placeholder="请输入过敏源"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      
      <!-- 图片上传 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="套餐图片" prop="coverImage">
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleImageChange"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              multiple
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="visible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" style="background-color: #4C6EE2;color: white;" :loading="submitting">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import { uploading } from '@/api/cuisine'
import { ComboUpdate,ComboAdd } from '@/api/combo'
import { listData } from "@/api/system/dict/data"
import { getList as getlists } from '@/api/cuisine'

export default {
  name: "combodialogull",
    dicts: ['foot_cuisine_type',"food_eat_type"],

  props: {
    // 接收当前行数据
    row: {
      type: Object,
      required: true
    },
    // 控制弹框显隐
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      submitting: false,
      fileList: [],
      ingredientList: [],
      dictTypeOptions: [],
      form: {
        comboId: '',
        comboName: '',
        coverImage: '',
        price: null,
        originalPrice: null,
        num: null,
        startDate: "",
        openingHours: [],
        type: null,
        limitPerUser: -1,
        remark: '',
        status: '0',
        sort: 0,
        listItem: [],
        description: '',
        allergy: '',
        createBy: ''
      },
      rules: {
        comboName: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        num: [{ required: true, message: '请输入最大供应量', trigger: 'blur' }],
        sort: [{ required: true, message: '请填写排序', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      moldList: [
        { value: 1, label: "早餐" },
        { value: 2, label: "午餐" },
        { value: 3, label: "晚餐" }
      ],
      statusList: [
        { value: 0, label: "正常" },
        { value: 1, label: "停用" }
      ],
      openingHoursList: [
        { value: 1, label: "周一" }, { value: 2, label: "周二" },
        { value: 3, label: "周三" }, { value: 4, label: "周四" },
        { value: 5, label: "周五" }, { value: 6, label: "周六" },
        { value: 7, label: "周日" }
      ]
    };
  },
  computed: {
    totalPrice() {
      return this.form.listItem.reduce((sum, item) => {
        const matchedIngredient = this.ingredientList.find(ing => ing.foodId === item.foodDish.foodId);
        return sum + (matchedIngredient?.price || 0);
      }, 0);
    },
    canChangeStatus() {
      // 判断是否有权限修改状态
      if (!this.$store || !this.$store.state?.user?.permissions) {
        return true;
      }
      return this.$store.state.user.permissions.includes("food:combo:approval");
    }
  },
  watch: {
    // 当弹框显示或数据变化时初始化表单
      visible(newVal) {
        console.log(123)
      if (newVal) {
        this.initData();
      }
    },
    row(newVal) {
      if (newVal && this.visible) {
        this.initData();
      }
    }
  },
    created() {
    console.log(6666)
    this.loadDependencies();
  },
  methods: {
    // 加载依赖数据
    async loadDependencies() {
      try {
        // 获取菜品类型字典
        const dictRes = await listData({ dictType: 'foot_cuisine_type', pageSize: 99 });
        this.dictTypeOptions = dictRes.rows || [];

        // 获取菜品列表
        const ingredientsRes = await getlists({ pageNum: 1, pageSize: 9999 });
        this.ingredientList = ingredientsRes.rows || [];
      } catch (error) {
        console.error("加载依赖数据失败:", error);
        this.$message.error("加载数据失败，请刷新页面重试");
      }
    },

    // 初始化表单数据
    initData() {
      if (!this.row) return;

      this.fileList = [];
      const rowData = { ...this.row };

      // 处理开放时间
      rowData.openingHours = [];
      for (let i = 1; i <= 7; i++) {
        if (rowData[`day${i}`] === 1) {
          rowData.openingHours.push(i);
        }
        delete rowData[`day${i}`];
      }

      // 处理菜品列表
      if (!Array.isArray(rowData.listItem) || rowData.listItem.length === 0) {
        rowData.listItem = [{ 
          foodDish: { foodId: '', type: '', foodName: '' } 
        }];
      } else {
        rowData.listItem = rowData.listItem.map(item => ({
          ...item,
          foodDish: item.foodDish || { foodId: '', type: '', foodName: '' }
        }));
      }

      // 处理状态为字符串
      rowData.status = String(rowData.status);
      
      // 处理图片
      try {
        const images = JSON.parse(rowData.coverImage || '[]');
        this.fileList = images.map(img => ({
          name: img.name || 'image',
          url: img.url
        }));
      } catch (e) {
        this.fileList = [];
      }

      // 设置创建人
      rowData.createBy = this.$store?.state?.user?.name || '';
      
      this.form = rowData;
    },

    // 关闭弹框
    handleClose() {
      this.$emit('update:visible', false);
      this.$refs.foodForm?.resetFields();
    },

    // 输入数量限制
    OnchangeInput(val) {
      if (this.form.limitPerUser > 0 && val > this.form.limitPerUser) {
        this.form.num = this.form.limitPerUser;
        this.$message.warning('超过最大限购数量');
      }
    },

    // 添加菜品
    addIngredients() {
      this.form.listItem.push({
        foodDish: {
          foodName: "",
          foodId: "",
          type: ""
        }
      });
    },

    // 删除菜品
    deleteFoodItems(index) {
      this.form.listItem.splice(index, 1);
    },

    // 菜品选择变化
    handleFoodChange(selectedFoodId, item) {
      const isValid = this.ingredientList.some(
        food => food.foodId === selectedFoodId && food.status !== 1
      );
      
      if (!isValid) {
        item.foodDish.foodId = '';
        this.$message.warning('所选菜品无效或已停用');
      }
    },

    // 图片上传前校验
    beforeUpload(file) {
      const isImage = file.type.includes('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isImage) {
        this.$message.error('只能上传图片文件！');
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB！');
      }
      
      return isImage && isLt5M;
    },

    // 处理图片变化
    async handleImageChange(file, fileList) {
      this.fileList = fileList;
      if (file.status === 'ready') {
        try {
          const formData = new FormData();
          formData.append('file', file.raw);
          
          const response = await uploading(formData);
          if (response.code === 200) {
            // 更新文件列表
            const index = this.fileList.findIndex(item => item.uid === file.uid);
            if (index !== -1) {
              this.$set(this.fileList[index], 'url', response.data);
              this.$set(this.fileList[index], 'name', file.name);
              this.$set(this.fileList[index], 'status', 'success');
            }
            
            // 更新表单图片数据
            this.form.coverImage = JSON.stringify(this.fileList);
            this.$message.success('图片上传成功');
          } else {
            throw new Error(response.msg || '上传失败');
          }
        } catch (error) {
          console.error('上传失败:', error);
          this.$message.error(error.message);
          this.fileList = this.fileList.filter(f => f.uid !== file.uid);
        }
      }
    },

    // 移除图片
    handleRemove(file, fileList) {
      this.fileList = fileList;
      
      // 更新表单图片数据
      this.form.coverImage = JSON.stringify(this.fileList);
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.foodForm.validate();
        this.submitting = true;
        
        // 处理菜品信息
        this.form.listItem.forEach(item => {
          const foodInfo = this.ingredientList.find(ing => ing.foodId === item.foodDish.foodId);
          if (foodInfo) {
            item.foodDish.foodName = foodInfo.foodName;
            item.foodDish.foodCode = foodInfo.foodCode;
            item.foodCode = foodInfo.foodCode;
            item.foodId = foodInfo.foodId;
          }
        });

        // 处理开放时间
        for (let i = 1; i <= 7; i++) {
          this.form[`day${i}`] = 0;
        }
        this.form.openingHours.forEach(day => {
          this.form[`day${day}`] = 1;
        });
        delete this.form.openingHours;

        // 处理权限相关状态
        if (!this.canChangeStatus) {
          this.form.status = 2; // 审核中
        }

        // 提交更新
        console.log(this.form)
        const response = await ComboUpdate(this.form);
        this.$message.success(response.msg || '更新成功');
        
        // // 关闭弹框并通知父组件刷新
        this.$emit('update:visible', false);
        this.$emit('update-success');
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error(error.msg || error.message || '提交失败，请重试');
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style scoped>

.el-input-number {
  width: 100%;
}
::v-deep .el-dialog__headerbtn .el-dialog__close {
  font-size: 25px;
}
::v-deep .el-dialog {
  border-radius: 15px;
}
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}
::v-deep .el-dialog__body {
  padding-top: 8px;
}
::v-deep .el-form-item {
  margin-bottom: 8px;
  margin-right: 0;
}
::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
::v-deep .dialogN .el-input--medium .el-input__inner {
  height: 42px;
  line-height: 42px;
}
</style>
